// #include "TcpServer.hpp"
#include <iostream>
#include <time.h>
#include <string>
#include <cassert>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"

void Usage(const std::string& proc)
{
    std::cout << "\nUsage: " << proc << " serverip serverport\n" << std::endl;
}

int main(int argc, char** argv)
{   
    if(argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    uint16_t serverport = std::stoi(argv[2]);
    std::string serverip = argv[1];
    Sock sockfd;
    sockfd.Socket();
    bool r = sockfd.Connect(serverip ,serverport);
    if(!r)  return 2;

    srand(time(nullptr) ^ getpid());

    const std::string opers = "+-*/%=^&";
    int cnt = 0;
    std::string recvMsg;
    while(cnt++ <= 20)
    {
        std::cout << "======================第" << cnt << "次测试============================" << std::endl;
        int data1 = rand() % 100 + 1;
        usleep(1234);
        int data2 = rand() % 50;
        usleep(4321);
        char oper = opers[rand() % opers.size()];
        Request req(data1, data2, oper);
        req.DebugPrint();

        std::string sendMsg;
        req.Serialize(&sendMsg);

        sendMsg = Encode(sendMsg);
        std::cout << "这是最新的发出去的请求: \n" << sendMsg;
        write(sockfd.Fd(), sendMsg.c_str(), sendMsg.size());

        // 客户端有可能一次发送了多个报文
        // write(sockfd.Fd(), sendMsg.c_str(), sendMsg.size());
        // write(sockfd.Fd(), sendMsg.c_str(), sendMsg.size());
        // write(sockfd.Fd(), sendMsg.c_str(), sendMsg.size());

        char buffer[1024];
        ssize_t n = read(sockfd.Fd(), buffer, sizeof(buffer)); // 无法保证读取到一个完整的报文
        if(n > 0)
        {
            buffer[n] = 0;
            recvMsg += buffer;  // "len\nresult code\n"
            std::cout << recvMsg << std::endl;
            std::string content;
            bool r = Decode(recvMsg, &content);  //"result code"
            assert(r);

            Response resp(0, 0);
            resp.Deserialize(content);
            assert(r);

            resp.DebugPrint();
        }
        // std::cout << "=======================================================================" << std::endl;
        sleep(1);
    }

    sockfd.Close(); 
    return 0;
}